<?php
include __DIR__ . "/config/cors.php";
include __DIR__ . "/database.php";

$nid = @$_POST['nid'];
$newImg = @$_POST['newImg'];
$title = @$_POST['title'];
$context = @$_POST['context'];


if (!isset($nid)) {
    echo json_encode([
        "code" => 201,
        "message" => "缺少必要参数"
    ]);
    exit;
} else if (!isset($title) or $title == "" or !isset($context) or $context == "") {
    echo json_encode([
        "code" => 201,
        "message" => "缺少标题或正文"
    ]);
    exit;
}

$db = new DB();
$sql = "select * from news where id = '$nid'";
$data = $db->selectOne($sql);
if (is_array($data) and count($data) > 0) {
    if(!isset($newImg) or $newImg == "") {
        $newImg = $data['newImg'];
    }
    $sql = "update news set title = '$title', context = '$context', newImg = '$newImg'
            where id = $nid";
    if ($db->execute($sql)) {
        echo json_encode([
            "code" => 200,
            "message" => "更新新闻成功"
        ]);
    } else {
        echo json_encode([
            "code" => 205,
            "message" => "更新新闻失败",
        ]);
    }
} else {
    echo json_encode([
        "code" => 202,
        "message" => "无此新闻"
    ]);
}